﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate.Context;
using System.Web;
using Microsoft.Practices.ServiceLocation;
using NHibernate;


namespace MM.Bootstrapper
{
    public class NHibernateCurrentSessionWebModule : IHttpModule
    {
        #region Miembros de IHttpModule
        
        public void Dispose() {
        }

        public void Init(HttpApplication context) {
            context.BeginRequest += new EventHandler(Application_BeginRequest);
            context.EndRequest += new EventHandler(Application_EndRequest);
        }

        #endregion

        private void Application_BeginRequest(object sender, EventArgs e) {
            ISession session = ServiceLocator.Current.GetInstance<ISessionFactory>().OpenSession();
            session.BeginTransaction();
            WebSessionContext.Bind(session);
            //CurrentSessionContext.Bind(session);
        }

        private void Application_EndRequest(object sender, EventArgs e) {

            //ISession session = CurrentSessionContext.Unbind(
            //ServiceLocator.Current.GetInstance<ISessionFactory>());

            ISession session = WebSessionContext.Unbind(
                ServiceLocator.Current.GetInstance<ISessionFactory>());

            if (session != null)
                try {
                    session.Transaction.Commit();
                }
                catch (Exception) {
                    session.Transaction.Rollback();
                    //throw;
                }
                finally {
                    session.Close();
                }
        }
    }
}
 
